﻿#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "mad.h"
#include <alsa/asoundlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "libmad_play.h"
#include "mp3player.h"
#include "kfifo.h"


#define MP3_FRAME_MAX_LEN 	1460
#define MP3_BUFF_SIZE 		1024*16*8   /*size必须是2的倍数*/

DECLARE_KFIFO(g_fifobuf, unsigned char, MP3_BUFF_SIZE); 
#define gbuf_in(p_data, len) kfifo_in(&g_fifobuf, p_data, len)
#define gbuf_out(p_data, len) kfifo_out(&g_fifobuf, p_data, len)
#define gbuf_init() do{INIT_KFIFO(g_fifobuf); printf("kfifo init %d\n", kfifo_avail(&g_fifobuf));}while(0)
#define gbuf_len() kfifo_len(&g_fifobuf)
#define gbuf_size() kfifo_size(&g_fifobuf)

/*
*/

void mp3_play_init(void)
{
    gbuf_init();
	libmad_media_init();
}

void mp3_buf_write(unsigned char *data, unsigned int len)
{
	if(len <= MP3_FRAME_MAX_LEN){
		len = gbuf_in(data, len); 
        //printf("mp3 in %d\n", len);
	}
	else{
		printf("mp3 data len too long\n");
	}
}
unsigned int mp3_buf_read(unsigned char *buf, unsigned int len)
{
    return gbuf_out(buf, len);
}

unsigned int mp3_buf_depth(void)
{
    unsigned int ret = 0;
    if(gbuf_size() > 0) {
        ret = (gbuf_len()*100)/gbuf_size();
    }
    return ret;
}

static volatile unsigned char media_sta = 0;

void mp3_media_open(void)
{
    unsigned int rate = 48000;;           		//采样频率
	const int channels = 2;                 	//声道数 2
    unsigned char sta = 1;
    if(media_sta != sta) {
	    libmad_media_start(rate, channels);
    }
    media_sta = sta;
}

void mp3_media_close(void)
{

    unsigned char sta = 0;
    if(media_sta != sta) {
	    libmad_media_stop();
    }
    media_sta = sta;
}






